package com.sc.pattern.pc;

import java.util.LinkedList;

/**
 * Created  on 2018/1/13.
 *
 * @author sc
 */
public class MessageQueue {
    private final LinkedList<Message> queue;
    private final static int DEFAULT_MAX = 100;
    private final int limit;
    public MessageQueue() {
        this(DEFAULT_MAX);
    }

    public MessageQueue(int limit) {
        this.limit = limit;
        this.queue = new LinkedList<>();
    }
    public void put(Message message) throws InterruptedException {
        synchronized (queue){
            while (queue.size()>limit){
                queue.wait();
            }
            queue.addLast(message);
            queue.notifyAll();
        }
    }

    public Message take() throws InterruptedException {
        synchronized (queue){
            while (queue.isEmpty()){
                queue.wait();
            }
            Message message = queue.removeFirst();
            queue.notifyAll();
            return message;
        }
    }
}
